from rest_framework import serializers
from .models import cartModel
from django.db import transaction
from goods.serializer import ProductSerializer
from goods.models import Product
from sku.serializer import SkuSerializer,attributeSerializer
from sku.models import Sku,skuAndAttribute,attribute
class CartSerializer(serializers.ModelSerializer):
    sku_id=serializers.CharField(write_only=True)
    sku_data=serializers.SerializerMethodField()
    goods_info=serializers.SerializerMethodField()
    class Meta:
        model = cartModel
        fields = ['id','num','sku_id','sku_data','goods_info','selected']
        extra_kwargs = {
            'goods_info':{
                'read_only':True
            },
            'sku_list':{
                'read_only':True
            },
            'sku_id':{
               'write_only':True
           },
            'selected':{
                'read_only':True
            }
        }
    def validate(self, attrs):
        attrs['User']=self.context['user']
        print(attrs)
        return attrs
    def create(self, validated_data):
        # 先判断是否存在该商品，如果存在就直接修改数量
        # 先从cartAndSku的第三张表中拿出所有的sku为18（前端传递）的cart的id
        cartObj=cartModel.objects.filter(sku=validated_data['sku_id'],User_id=validated_data['User']).first()
        if cartObj:
            cartObj.num=cartObj.num+validated_data['num']
            cartObj.save()
        else:
            cartObj=cartModel.objects.create(**validated_data)
        return cartObj
    def get_sku_data(self,obj):
        # 通过user拿出该用户所有的购物车对象
        # many=true的情况下，obj就是当前的购物车对象，通过购物车从第三张表中拿出所有的sku
        sku_Obj=Sku.objects.filter(id=obj.sku.id).first()
        # 一个购物车对象，必定只关联一个sku
        ser=SkuSerializer(sku_Obj)
        return ser.data
    def get_goods_info(self,obj):
        product=obj.sku.product
        ser=ProductSerializer(instance=product)
        return ser.data




